package com.gmall.console.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gmall.console.system.entity.Menu;
import com.gmall.console.system.mapper.MenuMapper;
import com.gmall.console.system.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Jone
 * @since 2024-05-30
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Override
    public List<Menu> getMenuList() {
        //查询一级菜单
        LambdaQueryWrapper<Menu> wrapper = new LambdaQueryWrapper();
        wrapper.eq(Menu::getParentId, 0);
        List<Menu> listMenu = this.list(wrapper);

        //再查询子菜单
        setMenuChildren(listMenu);
        return listMenu;
    }
    private void setMenuChildren(List<Menu> listMenu) {
        if(null != listMenu){
            for (Menu menu : listMenu) {
                LambdaQueryWrapper<Menu> subWrapper = new LambdaQueryWrapper();
                subWrapper.eq(Menu::getParentId,menu.getId());
                List<Menu> subListMenu = this.list(subWrapper);
                menu.setChildren(subListMenu);
                //递归，查询多级菜单
                setMenuChildren(subListMenu);
            }
        }
    }

    @Override
    public List<Menu> getMenuListByUser(String userId) {
        //查询一级菜单
        List<Menu> menuList = this.baseMapper.getMenuList(userId, 0);

        //再查询子菜单
        extracted(userId, menuList);

        return menuList;
    }

    private void extracted(String userId, List<Menu> menuList) {
        if(null != menuList){
            for (Menu menu : menuList) {
                List<Menu> subMenuList = this.baseMapper.getMenuList(userId, menu.getId());
                menu.setChildren(subMenuList);
                //递归，查询多级菜单
                extracted(userId,subMenuList);
            }
        }
    }

}
